<template>
  <el-cascader
    :value="value"
    :options="treeData"
    :props="props"
    separator="-"
    @change="handleChange"
  />
</template>
<script>
import { getDepartmentList } from '@/api/department'
export default {
  props: {
    value: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      treeData: [],
      props: { value: 'id', label: 'name', checkStrictly: true }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取部门列表，并转化为树形结构
    async getDepartment() {
      const res = await getDepartmentList()
      this.treeData = this.transList2Tree(res.filter(item => item.pid === 0), res)
    },
    transList2Tree(nodeList, list) {
      nodeList.forEach(item => {
        list.forEach(e => {
          if (item.id === e.pid) {
            if (item.children === undefined) item.children = []
            item.children.push(e)
          }
        })
        if (item.children !== undefined && item.children.length > 0) {
          this.transList2Tree(item.children, list)
        }
      })
      return nodeList
    },

    // 选中级联组件时将值传给父组件
    handleChange(list) {
      if (list.length) {
        this.$emit('input', list[list.length - 1])
      } else {
        this.$emit('input', null)
      }
    }
  }
}
</script>

